package com.echo.register.commons.rabbitMQ;

import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @program: com.echo.voter
 * @description: 消息发送
 * @author: Xiaoti
 * @create: 2018-11-05 16:37
 **/
@Service
public class MQSender {

    private static Logger logger = LoggerFactory.getLogger(MQSender.class);

    @Autowired
    AmqpTemplate amqpTemplate;

    public void sendVoteMessage(VoteMessage message){
        String msg = beanToString(message);
        logger.info("send message : " + msg);
        amqpTemplate.convertAndSend(MQConfig.VOTE_QUEUE, msg);
    }

    public void sendDetailMessage(DetailMessage message){
        String msg = beanToString(message);
        logger.info("send message : " + msg);
        amqpTemplate.convertAndSend(MQConfig.DETAIL_QUEUE, msg);
    }

    public void sendRecordsMessage(RecordsMessage message){
        String msg = beanToString(message);
        logger.info("send message :" + msg);
        amqpTemplate.convertAndSend(MQConfig.RECORDS_QUEUE, msg);
    }

    private <T> String beanToString(T value) {
        if(value == null){
            return null;
        }
        Class<?> clazz = value.getClass();
        if(clazz == int.class || clazz == Integer.class){
            return "" + value;
        }else if(clazz == String.class){
            return (String)value;
        }else if(clazz == long.class || clazz == Long.class){
            return "" + value;
        }else {
            return JSON.toJSONString(value);
        }
    }
}
